import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:fk_user_agent/fk_user_agent.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_taotaoshipin/value/constant.dart';
import 'package:flutter_taotaoshipin/value/sp_key.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:uuid/uuid.dart';
import 'package:package_info_plus/package_info_plus.dart';

/// https://medium.com/gskinner-team/flutter-simplify-platform-screen-size-detection-4cb6fc4f7ed1
class Device {
  static bool get isDesktop => !isWeb && (isWindows || isLinux || isMacOS);
  static bool get isMobile => isAndroid || isIOS;
  static bool get isWeb => kIsWeb;

  static bool get isWindows => !isWeb && Platform.isWindows;
  static bool get isLinux => !isWeb && Platform.isLinux;
  static bool get isMacOS => !isWeb && Platform.isMacOS;
  static bool get isAndroid => !isWeb && Platform.isAndroid;
  static bool get isFuchsia => !isWeb && Platform.isFuchsia;
  static bool get isIOS => !isWeb && Platform.isIOS;

  static late AndroidDeviceInfo androidInfo;
  static late IosDeviceInfo iosInfo;
  static late PackageInfo packageInfo;

  static Future<void> initDeviceInfo() async {
    final DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    if (isAndroid) {
      androidInfo = await deviceInfo.androidInfo;
    }
    if (isIOS) {
      iosInfo = await deviceInfo.iosInfo;
    }
    packageInfo = await PackageInfo.fromPlatform();
  }

  /// 使用前记得初始化
  static int getAndroidSdkInt() {
    if (isAndroid) {
      return androidInfo.version.sdkInt;
    } else {
      return -1;
    }
  }

  /// 设备id(imei或idfa) 或者 muid
  static String udid() {
    var uuid = '';
    if (isAndroid) {
      uuid = SpUtil.getString(SpKey.imei)!;
      if (uuid.isEmpty) {
        uuid = const Uuid().v1();
        SpUtil.putString(SpKey.imei, uuid);
      }
    }
    if (isIOS) {
      uuid = SpUtil.getString(SpKey.idfa)!;
    }

    return uuid;
  }

  /// us agent
  static String userAgent() {
    var ua = FkUserAgent.webViewUserAgent;
    return ua ?? 'Unknown';
  }

  /// 设备型号
  static String model() {
    var model = '';
    if (isAndroid) {
      model = androidInfo.model;
    }
    if (isIOS) {
      model = iosInfo.utsname.machine;
    }
    return model;
  }

  /// 设备标识 安卓传oaid IOS传idfv
  static String oaid() {
    var oaid = '';
    if (isAndroid) {
      // 取设备idfv，取不到自动生成一个保存
      oaid = SpUtil.getString(SpKey.oaid)!;
    }
    if (isIOS) {
      oaid = SpUtil.getString(SpKey.idfv)!;
      if (oaid.isEmpty) {
        // 取设备idfv，取不到自动生成一个保存
        oaid = iosInfo.identifierForVendor ?? const Uuid().v1();
        SpUtil.putString(SpKey.idfv, oaid);
      }
    }
    return oaid;
  }
}
